"""
Author: lrren01
Date: 2024-08-19 10:59:02
LastEditors: lrren01
LastEditTime: 2024-08-19 11:14:16
Description: componentDetect API
"""

# Create your views here.
from django.core.files.temp import NamedTemporaryFile
from django.http import JsonResponse, HttpResponse
import base64
import json
import os
import sys

sys.path.append(os.path.dirname(os.path.realpath(__file__)))
from component.model import componentDetect


def getComponentPosition(request):
    if request.method == "POST":
        data = json.loads(request.body)
        imgURL = data.get("imgURL")

        base64Str = imgURL.split(",")[1]
        padding = 4 - (len(imgURL) % 4)
        if padding:
            imgURL += "=" * padding
        imageBytes = base64.b64decode(base64Str)

        with NamedTemporaryFile(suffix=".png") as tempFile:
            tempFile.write(imageBytes)
            tempFile.flush()
            filePath = tempFile.name

        componentPosition, detectImg = componentDetect(filePath)

        responseData = {
            "componentPosition": componentPosition,
            "detectImg": detectImg,
        }

        response = HttpResponse(json.dumps(responseData))
        response["Access-Control-Allow-Origin"] = "*"
        response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
        response["Access-Control-Allow-Headers"] = "Content-Type"
        return response

    else:
        responseData = {"message": "不支持的请求方法"}
        return JsonResponse(responseData, status=405)
